package com.atguigu.service.impl;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.feign.ProductFeignClient;
import com.atguigu.order.bean.Order;
import com.atguigu.product.bean.Product;
import com.atguigu.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    DiscoveryClient discoveryClient;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    LoadBalancerClient loadBalancerClient;
    @Autowired
    ProductFeignClient productFeignClient;


    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallback") //定义资源
    @Override
    public Order createOrder(Long productId, Long userId) {
        Order order = new Order();
        //Product product = getProductFromRemoteWithLoadBalanceAnnotation(productId);
        Product product = productFeignClient.getProductById(productId);
        order.setUserId(userId);
        // 总金额
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setId(1L);
        order.setAddress("127.0.0.1");

        // 远程查询商品列表
        order.setProductList(Arrays.asList(product));
        return order;
    }

    //若"createOrder"违反规则，则调用createOrderFallback
    public Order createOrderFallback(Long productId, Long userId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setUserId(userId);
        order.setTotalAmount(BigDecimal.ZERO);
        order.setNickName("未知用户");
        order.setAddress("异常信息:" + e.getClass());
        return order;
    }

    private Product getProductFromRemote(Long productId) {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);

        //远程URL
        String address = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;

        RestTemplate restTemplate = new RestTemplate();
        log.info("远程请求：{}", address);
        return restTemplate.getForObject(address, Product.class);
    }

    //负载均衡发送请求
    private Product getProductFromRemoteWithLoadBalance(Long productId) {
        ServiceInstance instance = loadBalancerClient.choose("service-product");
        //远程URL
        String address = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;

        RestTemplate restTemplate = new RestTemplate();
        log.info("远程请求：{}", address);
        return restTemplate.getForObject(address, Product.class);
    }

    //基于注解的负载均衡
    private Product getProductFromRemoteWithLoadBalanceAnnotation(Long productId) {

        //"service-product"会被动态替换
        String address = "http://service-product/product/" + productId;

        log.info("远程请求：{}", address);
        return restTemplate.getForObject(address, Product.class);
    }
}
